package com.csun.cmny.provider.controller;

import com.csun.cmny.core.annotation.ValidateAnnotation;
import com.csun.cmny.core.support.BaseController;
import com.csun.cmny.provider.dao.OmcSchedulMonthMapper;
import com.csun.cmny.provider.dto.SchedulQueryDto;
import com.csun.cmny.provider.model.domain.OmcSchedul;
import com.csun.cmny.provider.model.domain.OmcSchedulMonth;
import com.csun.cmny.provider.model.dto.SchedulListDto;
import com.csun.cmny.provider.resolver.CmnyMessageSource;
import com.csun.cmny.provider.service.OmcSchedulMonthService;
import com.csun.cmny.provider.service.OmcScheduleService;
import com.csun.cmny.provider.validator.OmcScheduleAddValidator;
import com.csun.cmny.provider.vo.OmcSchedulMonthVo;
import com.csun.cmny.util.wrapper.WrapMapper;
import com.csun.cmny.util.wrapper.Wrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Pattern;

/*
 * 该模块涉及到排班方案，当选择某个方案后，要改变cn_omc_plan表达的isUsed字段，
 * *每使用一次方案自动加一，最大为9；
 * *每删除一个方案会自动减一，最小为0
 *
 * 通过方案id查询该方案的所有班次信息——PlanContreller Plan/selectById
 *
 * 筛选掉之前请假的需要前端处理——a.该组所有护工b.该组请假护工
 * 筛选掉之后请假的也是前端处理——同上，页面显示不同也是前端根据差异显示
 */
@RestController
@RequestMapping(value = "/schedule", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class OmcScheduleController extends BaseController {

    @Resource
    private CmnyMessageSource cmnyMessageSource;
    @Resource
    private OmcScheduleService omcSchedulService;
    @Resource
    private OmcSchedulMonthService omcSchedulMonthService;

    /**
     * 排班计划-保存
     * @param: [schedulListDto, br]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @ValidateAnnotation
   // @LogAnnotation
    @PostMapping(value = "/save")
    public Wrapper saveSchedul(@Validated(OmcScheduleAddValidator.class)
                                @RequestBody SchedulListDto schedulListDto,
                                BindingResult br) {

        List<OmcSchedul> omcSchedulList = schedulListDto.getOmcSchedulList();

        //校验排班计划是否为空
        if(omcSchedulList == null || omcSchedulList.size() < 1){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.null", null));
        }
        for(int j=0;j<=omcSchedulList.size()-1;j++){

            //校验交班id、计划id、周数
            if(omcSchedulList.get(j).getShiftsId() == null || omcSchedulList.get(j).getShiftsId() <= 0 || omcSchedulList.get(j).getShiftsId() > 2147483647){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.shiftsId.null", null));
            }
            if(omcSchedulList.get(j).getPlanId() == null || omcSchedulList.get(j).getPlanId() <= 0 || omcSchedulList.get(j).getPlanId() > 2147483647){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.planId.null", null));
            }
            if(omcSchedulList.get(j).getWeek() == null || omcSchedulList.get(j).getWeek() <= 0 || omcSchedulList.get(j).getWeek() > 2147483647){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.week.null", null));
            }
            //校验日期格式
            String pattern = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])"
                    + "|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|"
                    + "[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
            if (StringUtils.isNotBlank(omcSchedulList.get(j).getMonDate()) && !Pattern.matches(pattern, omcSchedulList.get(j).getMonDate())) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.dateMon.error", null));
            }
            if (StringUtils.isNotBlank(omcSchedulList.get(j).getTueDate()) && !Pattern.matches(pattern, omcSchedulList.get(j).getTueDate())) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.dateTue.error", null));
            }
            if (StringUtils.isNotBlank(omcSchedulList.get(j).getWedDate()) && !Pattern.matches(pattern, omcSchedulList.get(j).getWedDate())) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.dateWed.error", null));
            }
            if (StringUtils.isNotBlank(omcSchedulList.get(j).getThuDate()) && !Pattern.matches(pattern, omcSchedulList.get(j).getThuDate())) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.dateThu.error", null));
            }
            if (StringUtils.isNotBlank(omcSchedulList.get(j).getFriDate()) && !Pattern.matches(pattern, omcSchedulList.get(j).getFriDate())) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.dateFri.error", null));
            }
            if (StringUtils.isNotBlank(omcSchedulList.get(j).getSatDate()) && !Pattern.matches(pattern, omcSchedulList.get(j).getSatDate())) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.dateSat.error", null));
            }
            if (StringUtils.isNotBlank(omcSchedulList.get(j).getSunDate()) && !Pattern.matches(pattern, omcSchedulList.get(j).getSunDate())) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource.getMessage("scheaduleList.dateSun.error", null));
            }
        }

        //保存
        Integer result = omcSchedulService.saveSchedul(schedulListDto, getLoginAuthDto());
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    /**
     * 排班计划-查询
     * @param: [schedulQueryDto, br]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @ValidateAnnotation
  //  @LogAnnotation
    @RequestMapping(value = "/queryScheduleList" , method = RequestMethod.POST)
    public Wrapper queryScheduleList(@RequestBody SchedulQueryDto schedulQueryDto , BindingResult br){

        OmcSchedul omcSchedul = new OmcSchedul();
        BeanUtils.copyProperties(schedulQueryDto,omcSchedul);

        List<OmcSchedul> schedulList = omcSchedulService.queryScheduleList(omcSchedul,getLoginAuthDto());

        //return WrapMapper.ok(formatScheduleList(schedulList));
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),formatScheduleList(schedulList));
    }

    /**
     * 排班计划-管理员审批
     * @param: [schedulListDto, br]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @ValidateAnnotation
   // @LogAnnotation
    @RequestMapping(value = "/approvalSchedule" , method = RequestMethod.POST)
    public Wrapper approvalSchedule(@RequestBody SchedulListDto schedulListDto , BindingResult br){

        Integer ret = omcSchedulService.approvalSchedule(schedulListDto,getLoginAuthDto());
        if (ret < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //return WrapMapper.ok(ret);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),ret);
    }

    /**
     * 查询所有班次的负责人
     * 当查询到的list里面的负责人是空的时，说明之前排班计划的时候该班次该天没有安排人
     * @param: [schedulQueryDto]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @ValidateAnnotation
   // @LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @PostMapping(value = "/queryShiftUsers")
    public Wrapper queryShiftUsers(@RequestBody SchedulQueryDto schedulQueryDto){

        OmcSchedul omcSchedul = new OmcSchedul();
        BeanUtils.copyProperties(schedulQueryDto,omcSchedul);

        List<OmcSchedul> omcSchedulList = omcSchedulService.queryShiftUsers(omcSchedul,getLoginAuthDto());

        //return WrapMapper.ok(formatScheduleList(omcSchedulList));
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),formatScheduleList(omcSchedulList));
    }

    /**
     * 排班计划-删除
     *
     * @param: [schedulQueryDto]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @ValidateAnnotation
    //@LogAnnotation(isSaveRequestData = true, isSaveResponseData = true)
    @PostMapping(value = "/delete")
    public Wrapper deleteScheadule(@RequestBody SchedulQueryDto schedulQueryDto){

        OmcSchedul omcSchedul = new OmcSchedul();

        if(schedulQueryDto.getWeek() == null || schedulQueryDto.getWeek() == 0){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("scheaduleList.week.null", null));
        }

        BeanUtils.copyProperties(schedulQueryDto,omcSchedul);

        int ret = omcSchedulService.deleteScheadule(omcSchedul,getLoginAuthDto());

        //return WrapMapper.ok(ret);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),ret);
    }



    /**
     * 处理用户姓名、id,由String转化为list
     * @param: [omcSchedulList]
     * @return: java.util.List<com.csun.cmny.provider.model.domain.OmcSchedul>
     */
    public List<OmcSchedul> formatScheduleList(List<OmcSchedul> omcSchedulList){

        //将护工字符串处理为集合
        //外层根据该计划有几个班次进行循环
        if(omcSchedulList == null || omcSchedulList.size() <1){
            return null;
        }
        for(int i=0;i<=omcSchedulList.size()-1;i++){
            //获取一周中每天的userId数组、userName数组
            OmcSchedul omcSchedul = omcSchedulList.get(i);

            if(omcSchedul.getMonUserId() != null && omcSchedul.getMonUserId() != ""
                && omcSchedul.getMonRealName() != null && omcSchedul.getMonRealName() != ""
            ){
                omcSchedul.setMonUserIdArray(omcSchedul.getMonUserId().split("-"));
                omcSchedul.setMonUserNameArray(omcSchedul.getMonRealName().split("-"));
            }

            if(omcSchedul.getTueUserId() != null && omcSchedul.getTueUserId() != ""
                && omcSchedul.getTueRealName() != null && omcSchedul.getTueRealName() != ""
            ){
                omcSchedul.setTueUserIdArray(omcSchedul.getTueUserId().split("-"));
                omcSchedul.setTueUserNameArray(omcSchedul.getTueRealName().split("-"));
            }

            if(omcSchedul.getWedUserId() != null && omcSchedul.getWedUserId() != ""
                && omcSchedul.getWedRealName() != null && omcSchedul.getWedRealName() != ""
            ){
                omcSchedul.setWedUserIdArray(omcSchedul.getWedUserId().split("-"));
                omcSchedul.setWedUserNameArray(omcSchedul.getWedRealName().split("-"));
            }

            if(omcSchedul.getThuUserId() != null && omcSchedul.getThuUserId() != ""
                && omcSchedul.getThuRealName() != null && omcSchedul.getThuRealName() != ""
            ){
                omcSchedul.setThuUserIdArray(omcSchedul.getThuUserId().split("-"));
                omcSchedul.setThuUserNameArray(omcSchedul.getThuRealName().split("-"));
            }

            if(omcSchedul.getFriUserId() != null && omcSchedul.getFriUserId() != ""
                && omcSchedul.getFriRealName() != null && omcSchedul.getFriRealName() != ""
            ){
                omcSchedul.setFriUserIdArray(omcSchedul.getFriUserId().split("-"));
                omcSchedul.setFriUserNameArray(omcSchedul.getFriRealName().split("-"));
            }

            if(omcSchedul.getSatUserId() != null && omcSchedul.getSatUserId() != ""
                && omcSchedul.getSatRealName() != null && omcSchedul.getSatRealName() != ""
            ){
                omcSchedul.setSatUserIdArray(omcSchedul.getSatUserId().split("-"));
                omcSchedul.setSatUserNameArray(omcSchedul.getSatRealName().split("-"));
            }

            if(omcSchedul.getSunUserId() != null && omcSchedul.getSunUserId() != ""
                && omcSchedul.getSunRealName() != null && omcSchedul.getSatRealName() != ""
            ){
                omcSchedul.setSunUserIdArray(omcSchedul.getSunUserId().split("-"));
                omcSchedul.setSunUserNameArray(omcSchedul.getSunRealName().split("-"));
            }
        }
        return omcSchedulList;
    }

    /**
     * 查询护工组月计划
      * @param omcSchedulMonthVo
     * @return Wrapper
     * @author HD
     * @date  14:04
     */
    @PostMapping("/getSchedulMonth")
    public Wrapper getSchedulMonth(@RequestBody OmcSchedulMonthVo omcSchedulMonthVo){
        List<OmcSchedulMonth> omcSchedulMonth = omcSchedulService.queryScheduleMonthList(omcSchedulMonthVo,getLoginAuthDto());

        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),omcSchedulMonth);
    }

    /**
     * 保存排班计划(月)
      * @param omcSchedulMonth
     * @return Wrapper
     * @author HD
     * @date 2021/12/6 15:54
     */
    @PostMapping("/saveSchedulMonth")
    public Wrapper saveSchedulMonth(@RequestBody OmcSchedulMonth omcSchedulMonth){
        if(omcSchedulMonth.getNursingGroupId() == null){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("nursingGroupId.null", null));
        }
        if(omcSchedulMonth.getMonth() == null){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("nursing.month.null", null));
        }
        omcSchedulMonth.setGroupId(getLoginAuthDto().getGroupId());
        omcSchedulMonth.setUpdateInfo(getLoginAuthDto());
        //查询本月是否已有排班计划
        OmcSchedulMonth schedulMonth = new OmcSchedulMonth();
        schedulMonth.setMonth(omcSchedulMonth.getMonth());
        schedulMonth.setNursingGroupId(omcSchedulMonth.getNursingGroupId());
        List<OmcSchedulMonth> select = omcSchedulMonthService.select(schedulMonth);
        if(select.size() > 0 && select.get(0).getId() != omcSchedulMonth.getId()){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("nursing.not.null", null));
        }
        Integer result = omcSchedulMonthService.saveSchedulMonth(omcSchedulMonth);
        if (result < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }

        //return WrapMapper.ok(result);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),result);
    }

    /**
     * 排班计划(月)-管理员审批
     * @param: [schedulListDto, br]
     * @return: com.csun.cmny.util.wrapper.Wrapper
     */
    @RequestMapping(value = "/approvalScheduleMonth" , method = RequestMethod.POST)
    public Wrapper approvalScheduleMonth(@RequestBody OmcSchedulMonth omcSchedulMonth){

        Integer ret = omcSchedulMonthService.approvalScheduleMonth(omcSchedulMonth);
        if (ret < 1) {
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        //return WrapMapper.ok(ret);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),ret);
    }

    /**
      * @param omcSchedulMonth
     * @return Wrapper
     * @author HD
     * @date 2021/12/6 19:33
     */
    @PostMapping("/deleteScheduleMonth")
    public Wrapper deleteScheduleMonth(@RequestBody OmcSchedulMonth omcSchedulMonth){
        OmcSchedulMonth schedulMonth = omcSchedulMonthService.selectByKey(omcSchedulMonth);
        if(schedulMonth.getStatus() > 0){
            return WrapMapper.wrap(Wrapper.ERROR_CODE, cmnyMessageSource
                    .getMessage("operation.failed", null));
        }
        int ret = omcSchedulMonthService.deleteByKey(omcSchedulMonth.getId());

        //return WrapMapper.ok(ret);
        return WrapMapper.wrap(Wrapper.SUCCESS_CODE, cmnyMessageSource
                .getMessage("operation.success", null),ret);
    }

}
